<?php
/*------------------------------------------------------------------
 | Software: APHP - A PHP TOP Framework
 | Site: https://aphp.top
 |------------------------------------------------------------------
 | (C)2020-2024 无念<24203741@qq.com>,All Rights Reserved.
 |-----------------------------------------------------------------*/
declare(strict_types=1);

namespace app\index\controller;

use aphp\core\Jump;
use extend\captcha\Captcha;

class User
{
    use Jump;
    protected array $middleware = [
        'auth' => ['except' => ['login', 'logout', 'register', 'captcha']],
    ];

    // 登录
    public function login(array $req)
    {
        if ($this->isPost()) {
            $model = model('user');
            $r = $model->login($req);
            $this->_jump(['登录成功', $model->getError()], $r, 'index/index');
        }
        return view();
    }

    // 退出
    public function logout()
    {
        session(null);
        $this->success('退出成功', 'user/login');
    }

    // 注册
    public function register(array $req)
    {
        if ($this->isPost()) {
            $r = model('user')->save($req);
            $this->_jump(['注册成功', '注册失败'], $r, 'login?from=' . $req['username']);
        }
        return view();
    }

    // 验证码
    public function captcha()
    {
        return (new Captcha())->make();
    }

    // 会员中心
    public function index()
    {
        $user = model('user')->find(session('user.id'));
        return view()->with(['vo' => $user->toArray()]);
    }

    // 修改资料
    public function edit(array $req)
    {
        $user = model('user')->find(session('user.id'));
        if ($this->isPost()) {
            $r = $user->save($req);
            $this->_jump(['修改成功', '修改失败'], $r, 'index');
        }
        return view()->with('vo', $user->toArray());
    }

    // 修改密码
    public function password(array $req)
    {
        if ($this->isPost()) {
            $user = model('user');
            $r = $user->changePassword($req);
            $this->_jump(['修改成功', $user->getError()], $r, 'index');
        }
        return view();
    }

    public function buy(int $id)
    {
        $this->error('ok-'.$id);
    }
}